﻿namespace CombinatorialObjects
{
    public class LazyArray<T>
    {
        private ArrayItemGetter _getter;
        private readonly T[] _array;
        private readonly bool[] _initialized;
        public delegate T ArrayItemGetter(int index);
        
        public LazyArray(int n, ArrayItemGetter getter)
        {
            _getter = getter;
            _array = new T[n];
            _initialized = new bool[n];
        }

        public int Length
        {
            get { return _array.Length; }
        }
        public T[] Array
        {
            get { return _array; }
        }
        public T this[int index]
        {
            get
            {
                T ret;
                if (_initialized[index])
                    ret = _array[index];
                else
                {
                    ret = _array[index] = _getter(index);
                    _initialized[index] = true;
                }
                return ret;
            }
            set 
            {
                _array[index] = value;
                _initialized[index] = true;
            }
        }

        public int Lenght
        {
            get{ return _array.Length; }
        }

        public ArrayItemGetter Getter
        {
            get { return _getter; }
            set { _getter = value; }
        }
    }
}
